package com.mzy.basics.timer;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/5/17 19:13
 * @Version 1.0
 */
public class timerDemo1 {

    private static volatile boolean clientConnect = false;

    public static void main(String[] args) {

        Timer timer = jian();


        String[] str2="123456".split("");

        // 每一秒钟执行一次
        final long timeInterval = 2000;
        Runnable runnable = () -> {
            while (true) {
                // ------- code for task to run
                // ------- 要运行的任务代码
                // ------- ends here
                try {
                    for (String c : str2) {
                        //如果不是2就一直返回空，直到运行打印，打印完之后把原子对象变成1
                        if (c.equals("5")){
                            System.out.println("连接成功，停止定时器轮询");
                            timer.cancel();
                        }
                        // sleep()：同步延迟数据，并且会阻塞线程
                        Thread.sleep(timeInterval);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        //创建定时器
        Thread thread = new Thread(runnable);
        //开始执行
        thread.start();
    }

    public static Timer jian(){
        Timer timer = new Timer();
        //void schedule(TimerTask task, long delay, long period)
        //在指定的延迟时间delay后，执行task任务，之后每隔period时间后再次执行task任务
        timer.schedule(new MyTask1(timer),0,2000);
        return timer;
    }
}


class MyTask1 extends TimerTask{
    private int count = 0;
    private Timer timer;

    public MyTask1(){}
    public MyTask1(Timer timer){
        this.timer = timer;
    }
    @Override
    public void run() {
        count++;
        System.out.println("时间到了,这时第 "+count+" 次执行此任务");
//        if(flag){
//            timer.cancel();
//        }
    }
}